package cn.virens.web.components.shiro.simple.simple;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.virens.database.common.TransactionExecute;
import cn.virens.database.mysql.model.sys.SysLog;
import cn.virens.database.mysql.model.sys.SysUser;
import cn.virens.database.service.sys.SysLogService;
import cn.virens.database.service.sys.SysUserService;

/**
 * 打印请求地址
 * 
 * @文件   :CustomUserFilter.java
 * @作者   :cn.loioi
 * @创建时间 :2016年10月13日 下午12:57:20
 */
public class SimpleUserFilter extends UserFilter {
	private Logger logger = LoggerFactory.getLogger(SimpleUserFilter.class);

	public final static String LOGIN_USER = "SESSION_USER";
	public final static String LOGIN_ROLE = "SESSION_ROLE";

	private @Autowired SysLogService mSysLogService;
	private @Autowired SysUserService mSysUserService;
	private @Autowired TransactionExecute transactionExecute;

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		logger.debug(((HttpServletRequest) request).getRequestURI());

		// 如果是登陆请求就放行
		if (isLoginRequest(request, response)) { return true; }

		// 获取认证令牌
		Subject subject = getSubject(request, response);
		if (subject == null) { return false; }

		// 获取当前登陆用户
		Object principal = subject.getPrincipal();
		if (principal == null) { return false; }

		// 获取缓存的用户信息，如果用户信息不存在就更新
		Session session = subject.getSession();
		Object sessionUser = session.getAttribute(LOGIN_USER);
		if (!(sessionUser instanceof SysUser)) {
			transactionExecute.readTransaction((s) -> {
				SysUser user = mSysUserService.getUser(principal.toString());
				SysLog role = mSysLogService.selectOne(user.getRoleId());

				// 将用户信息 & 角色信息 存入session
				session.setAttribute(LOGIN_USER, user);
				session.setAttribute(LOGIN_ROLE, role);
			});
		}

		return true;
	}
}
